﻿//表单插件类

define(function (require, exports, module) {
    require('./ActionJScript.js');
    require('./jshint.js');
    require('./FormXMLParser.js');
    WebPDF.FormPluginName = "Form Plugin";

    function ErrorResults(state, errMsg) {
        this.m_state = state;
        this.m_errMsg = errMsg;
    }

    /**
     * Form plugin
     * @param {WebPDF.ReaderApp} readerApp app instance
     * @extends {WebPDF.IReaderPlugin}
     * @constructor
     */
    WebPDF.CFormPlugin = function (readerApp) {
        var _readerApp = readerApp;
            //_self = this;

        /**
         * 是否允许填表
         * @type {boolean}
         * @private
         */
        var _canFillForm = false;
        /**
         * 表单域当前是否处于高亮状态
         * @type {boolean}
         * @private
         */
        var _isFieldsHighlight = true;
        var _initedPageList = {};
        var _initedPageListVisible = {};
        var _initedPageListNeedShow = {};
        var _initedPageListRequest = {};
        var _tabNum = 0;
        
        var _requiredFieldList = null;
        var _bGetRequiredFieldList = false;

        //获取Plugin名称;
        this.getPluginName = function () {
            return WebPDF.FormPluginName;
        };
        //插件被注册的时候调用;
        this.onRegister = function () {
        };
        
        function _ajaxGetFormRequiredFieldXml(retryCount) {
            if (_bGetRequiredFieldList) return;
        	var pageNumbersStr = encodeURIComponent("RequiredField");
            var formXmlUrl = _readerApp.getOptions().url + "form/xml/" + pageNumbersStr;
            if (retryCount <= 0) {
            	console.error('Maximum number of retries exceeded for get form required field xml request.');
            	return;
            }

            _bGetRequiredFieldList = true;
            var requestData = {};
            requestData.s3Key = readerApp.getFileID();
            $.ajax({
                url: formXmlUrl,
                dataType: 'xml',
                data:requestData,
				contentType:"application/x-www-form-urlencoded",
                success: function (xmlData) {
                	_bGetRequiredFieldList = false;
                	var errorResults = _checkError(xmlData);
                    var docView = _readerApp.getMainView().getDocView();
                    if (errorResults) {
                        if (WebPDF.Common.isNeedRetry(errorResults.m_state)) {
                        	var progress = docView.getPageViewRender().getMaxRenderedPageIndex();
                        	if(progress == null) {
                                progress = 0;
                            }
                           
                            var interval = WebPDF.AjaxRetryManager.getNextFormXmlRequestInterval(0,progress,
                                docView.getPageCount());
                            setTimeout(function () { _ajaxGetFormRequiredFieldXml(retryCount - 1); },interval);
                            return;
                        }
                        console.error('Get Form Required Field XML Data Error:' + (errorResults.m_errMsg ? errorResults.m_errMsg : errorResults));
                        return;
                    }

                    _requiredFieldList = [];
                    $(xmlData).find("Page").each(function () {
                        var pageIndex = parseInt($(this).attr("PageNo"));
                        var tmpPage = [];
                        $(this).children('Widget').each(function () {
                        	tmpPage.push({"Name":WebPDF.getNodeString($(this), "Name"), 
                        		"Type":WebPDF.getNodeString($(this), "Type")});
                        });
                        _requiredFieldList[pageIndex] = tmpPage;
                    });
                },
                error: function () {
                    console.error('Get Form XML Data Error!');
                    _bGetRequiredFieldList = false;
                }
            });
        }

        //模块初始化;
        this.init = function () {
            var docType = _readerApp.getPDFDoc().getDocType();
            if (docType != WebPDF.PDFDocType.FORM && docType != WebPDF.PDFDocType.XFA){
                console.warn("The document is not a PDF form, form plugin will do nothing.");
                return;
            }
            var formFieldsContainerClass = 'fwr-form-fields-container';
            _readerApp.addIgnoreMouseEventClass(formFieldsContainerClass);
           
            var docPermission = _readerApp.getDocPermission();
            _canFillForm = (docPermission & 0x0010) == 0;

            if (_canFillForm) {
            	 _bindEvents();
            	 _ajaxGetFormRequiredFieldXml(WebPDF.Config.requestRetryCount);
                _showFormWidget();
            }
            
        };
        //模块卸载;
        this.unload = function () {
        };

        this.getReaderApp = function () {
            return _readerApp;
        };
        
        this.isFormFieldsEnable = function () {
        	var isEnable = _canFillForm;
            if (isEnable) {
                var pTool = _readerApp.getCurToolHandler();
                if (pTool != null && pTool.getName() != WebPDF.Tools.TOOL_NAME_HAND
                		/* && pTool.getName() != WebPDF.Tools.TOOL_NAME_INKANNOT*/) {
                    isEnable = false;
                }
            }
            return isEnable;
        };
        
        this.disableFormFields = function () {
        	_canFillForm = false;
        };

        /**
         * Get form data in XML format.
         * Note: this function will return empty string if the current PDF form can not be filled.
         */
        this.getFormData = function(){
            if (!_canFillForm){
                return "";
            }
            return WebPDF.g_formValue.GetFormDataXML();
        };
        
        /**
         * Import the form data in XML format.
         */
        this.setFormDataByXMLData = function(xmlData){
            if (!_canFillForm){
                return ;
            }
            WebPDF.g_formValue.SetFormDataByXML($(xmlData));
            this.updateForm();
        };
        
        /**
         * Check whether form data has been modified.
         */
        this.isModifiedFormData = function() {
        	var bModified = false;
        	if (_canFillForm){
        		for (var key in _initedPageList) {
                    if (_initedPageList[key] != null) {
                    	bModified = _initedPageList[key].isModifiedFormData();
                    	if (bModified)
                    		break;
                    }
                }
            }
        	return bModified;
        };
        
        /**
         * 依据WebPDF.g_formValue中值，更新各表单域
         * 
         * 下面参数用于缩小更新查找范围
         * @param {String} form filed name
         * @param {String} element id
         * 
         * @private
         */
        this.updateForm = function() {
        	if (!_canFillForm) return;
        	for (var key in _initedPageList) {
                if (_initedPageList[key] != null)
                	_initedPageList[key].update(arguments[0], arguments[1]);
            }
        };

        /**
         * Reset all of form fields.
         */
        this.resetForm = function() {
        	if (!_canFillForm) return;
        	WebPDF.g_formValue.ClearAll();
            var docView = _readerApp.getMainView().getDocView();
            var pageCnt = docView.getPageCount();
            for (var i = 0; i < pageCnt; i++) {
                var pageView = docView.getPageView(i);
                if (pageView != null && _initedPageList[i] != null) {
                    _initedPageList[i].resetData();
                }
            }
            _readerApp.setModified(null, null, true);
        };

        /**
         * Check whether all of required fields have been filled.
         * @returns {boolean} return true if all of required fields have been filled, otherwise return false.
         */
        this.checkRequiredField = function(){
        	if (!_canFillForm) return true;
        	if (_requiredFieldList == null) {
        		_ajaxGetFormRequiredFieldXml();
        		var docView = _readerApp.getMainView().getDocView();
                var pageCnt = docView.getPageCount();
                for (var i = 0; i < pageCnt; i++) {
                    var pageView = docView.getPageView(i);
                    if (pageView != null && _initedPageList[i] != null) {
                        if(!_initedPageList[i].CheckRequiredWidget()){
                            return false;
                        }
                    } else {
                    	return false;//必须所有页面表单域都加载显示出来
                    }
                }
        	} else {
        		for (var index in _requiredFieldList) {
        			if (_requiredFieldList[index]) {
        				if (_initedPageList[index] == null ||
        						!_initedPageList[index].CheckRequiredWidget()) {
        					return false;
        				}
        			}
        		}
        	}
            return true;
        };


        /**
         * Check whether current PDF form can be filled.
         * @returns {boolean} return true if current PDF form can be filled.
         */
        this.canFillForm = function(){
            return _canFillForm;
        };

        /**
         * Toggle highlight state.
         */
        this.toggleHighlight = function () {
        	if (!_canFillForm) return;
        	_isFieldsHighlight = !_isFieldsHighlight;
            for (var key in _initedPageList) {
                if (_initedPageList[key] != null)
                	_initedPageList[key].changeHighlight(_isFieldsHighlight);
            }
        };

        this.isHighlight = function(){
            return _isFieldsHighlight;
        };

        this.getInitializedPageList = function(){
            return _initedPageList;
        };

        function _checkError(xmlData) {
            var ret = null;
            if (xmlData == null) {
                return "Loading failed, the link is corrupted or tampered.";
            }
            $(xmlData).find("Pages").each(function () {
                if (WebPDF.getNodeString($(this), "Error") == "Error") {
                    var errMsg = WebPDF.getNodeString($(this), "Msg");
                    var state = WebPDF.getNodeFloat($(this), "status");
                    ret = new ErrorResults(state, errMsg);
                }
            });
            return ret;
        }

        function _ajaxGetFormXml(pageNumArr, retryCount) {
            var pageNumbersStr = pageNumArr.join(";");
            pageNumbersStr = encodeURIComponent(pageNumbersStr);
            var formXmlUrl = _readerApp.getOptions().url + "form/xml/" + pageNumbersStr;
            if (retryCount <= 0) {
            	console.error('Maximum number of retries exceeded for get form xml request.');
            	return;
            }

            var requestData = {};
            requestData.s3Key = readerApp.getFileID();
            $.ajax({
                url: formXmlUrl,
                dataType: 'xml',
				contentType:"application/x-www-form-urlencoded",
				data:requestData,
                success: function (xmlData) {
                    var errorResults = _checkError(xmlData);
                    var docView = _readerApp.getMainView().getDocView();
                    if (errorResults) {
                        if (WebPDF.Common.isNeedRetry(errorResults.m_state)) {
                        	var progress = docView.getPageViewRender().getMaxRenderedPageIndex();
                        	if(progress == null) {
                                progress = 0;
                            }
                           
                            var interval = WebPDF.AjaxRetryManager.getNextFormXmlRequestInterval(pageNumArr[pageNumArr.length-1],progress,
                                docView.getPageCount());
                            setTimeout(function () { _ajaxGetFormXml(pageNumArr, retryCount - 1); },interval);
                            return;
                        }

                        for (var i in pageNumArr) {
                            _initedPageListVisible[pageNumArr[i]] = false;
                        }
                        console.error('Get Form XML Data Error:' + (errorResults.m_errMsg ? errorResults.m_errMsg : errorResults));
                        return;
                    }

                    $(xmlData).find("Page").each(function () {
                        var pageIndex = parseInt($(this).attr("PageNo"));
                        var pageView = docView.getPageView(pageIndex);
                        var pageID = pageView.getPageBackgroundImgID();
                        var tmpFormPage = new WebPDF.FormPage(_readerApp);
                        if (!_initedPageList[pageIndex]) {
                            tmpFormPage.parser(pageID + "_form", pageIndex, $(this));
                            _initedPageList[pageIndex] = tmpFormPage;
                            if (pageView.isPageLoaded()) {
                                if (pageView.isPageLoadError()) {
                                    _initedPageList[pageIndex] = null;
                                }
                                else {
                                    $("#" + pageID).after(tmpFormPage.getHtmlCode(_isFieldsHighlight));
                                    tmpFormPage.getRegisterActionCode();
                                    tmpFormPage.getReadyBindCode();
                                    if (_initedPageListVisible[pageIndex]){
                                        tmpFormPage.ShowPage();
                                    }
                                    tmpFormPage.changeSize(docView.getScale());
                                    _initedPageList[pageIndex].changeHighlight(_isFieldsHighlight);
                                }
                            }
                            else {
                                _initedPageListNeedShow[pageIndex] = true;
                            }
                        }
                        pageNumArr[pageIndex] = null;
                        _initedPageListRequest[pageIndex] = false;
                    });

                    for (var i in pageNumArr) {
                        if (pageNumArr[i] != null) {
                            _initedPageListVisible[pageNumArr[i]] = false;
                        }
                    }
                },
                error: function () {
                    for (var i in pageNumArr) {
                        _initedPageListVisible[pageNumArr[i]] = false;
                    }
                    console.error('Get Form XML Data Error!');
                }
            });
        }

        function _showFormWidget () {
            var docView = _readerApp.getMainView().getDocView();
            var visiblePageRange = docView.getVisiblePageRange();
            var pageNumArr = [];
            var pageCount = 0;
            for (var i = visiblePageRange.begin; i <= visiblePageRange.end; i++) {
                var pageView = docView.getPageView(i);
                if (!pageView.isPageLoadError()) {
                    if (_initedPageList[i]) {
                        if (!_initedPageListVisible[i]) {
                            _initedPageList[i].ShowPage();
                            _initedPageListVisible[i] = true;
                        }
                    }
                    else {
                        _initedPageListVisible[i] = true;
                        if (!_initedPageListRequest[i]) {
                            _initedPageListRequest[i] = true;
                            pageNumArr[pageCount++] = i;
                        }
                    }
                }
            }
            if (pageNumArr.length > 0) {
                _ajaxGetFormXml(pageNumArr, WebPDF.Config.requestRetryCount);
            }
        }

        function _bindEvents(){
            var docView = _readerApp.getMainView().getDocView();
            $(_readerApp).on(WebPDF.EventList.DOCVIEW_PRE_RESIZE, function(){
                _onPreDocViewResize();
            }).on(WebPDF.EventList.PAGE_INVISIBLE, function(event,data){
                var pages = data.pages;
                for(var i in  pages){
                    var pageView = docView.getPageView(i);
                    _initedPageListVisible[pageView.getPageIndex()] = false;
                }

            }).on(WebPDF.EventList.PAGE_SHOW_COMPLETE,function(event,data){
            	_showFormWidget();
            	_onPageShowComplete(data.pageView);
            }).on(WebPDF.EventList.PAGE_VISIBLE, function(event,data){
                _showFormWidget();
            }).on(WebPDF.EventList.DOCVIEW_PAGE_CHANGED,function(event,data){
                _showFormWidget();
                _tabNum = 0;
            });

            
			var docViewContainerID = docView.getDocViewContainerID();
            
            $("#" + docViewContainerID).on("keydown",".fwr-form-fields-container",function(e){
        		var pageIndex = docView.getCurPageIndex();
            	if(pageIndex >= docView.getPageCount())return;
            	var formPage = _initedPageList[pageIndex];
            	if(!formPage)return;
            	
            	var isie = (document.all) ? true:false; 
            	var key; 
            	var ev; 
            	if(isie){ 
	            	key = window.event.keyCode; 
	            	ev = window.event; 
            	}else{
            		key = e.which; 
            		ev = e; 
            	} 
                if(e.keyCode == "9"){
                	if(isie){ 
	                	ev.keyCode=0; 
	                	ev.returnValue=false; 
                	}else{
	                	ev.which=0; 
	                	ev.preventDefault(); 
                	} 
                
                	if(pageIndex == docView.getPageCount() - 1 && (_tabNum == formPage.formWidgets.length - 1 || formPage.formWidgets.length == 0)){
                		docView.goToPage(0);
                		formPage = _initedPageList[0];
                		_tabNum = 0;
                	}
                	_nextFormWideget(formPage);                	
                }
            })
        }

        function _onPageShowComplete  (pageView) {
            var pageIndex = pageView.getPageIndex();
            if (_initedPageListNeedShow[pageIndex]) {
                if (pageView.isPageLoadError()) {
                    _initedPageList[pageIndex] = null;
                }
                else {
                    var formPage = _initedPageList[pageIndex];
                    if (formPage) {
                    	var pageID = pageView.getPageBackgroundImgID();
                        _initedPageListNeedShow[pageIndex] = false;
                        $("#" + pageID).after(formPage.getHtmlCode(_isFieldsHighlight));
                        formPage.getRegisterActionCode();
                        formPage.getReadyBindCode();
                        if (_initedPageListVisible[pageIndex]){
                            formPage.ShowPage();
                        }
                        formPage.changeSize(pageView.getDocView().getScale(), true);
                    }
                }
            }
			return true;
        }
        
        function _nextFormWideget(formPage){
        	var docView = _readerApp.getMainView().getDocView();
        	var pageIndex = docView.getCurPageIndex();
        	if(formPage.formWidgets.length == 0){
        		docView.goToNextPage();
        		return;
        	};
        	var noFocus = true;
			for(var i = 0; i < formPage.formWidgets.length; i++ ){
				if( !formPage.formWidgets[i] || formPage.formWidgets[i].formWidget.bReadOnly)continue;
        		if(formPage.formWidgets[i].formWidget.onfocus){
        			_tabNum = i;
        			noFocus = false;
        			break;
        		}
        	}
        	
			if(_tabNum == formPage.formWidgets.length - 1){
				if(pageIndex < docView.getPageCount() - 1){
					docView.goToNextPage();
					formPage = _initedPageList[pageIndex + 1];
				}else{
					docView.goToPage(0);
					formPage = _initedPageList[0];
				}
				_tabNum = 0;
				_nextFormWideget(formPage);
				return;
			}else if(noFocus && _tabNum == 0){
				_tabNum = 0;
			}else{
				_tabNum++;
			}

        	var formWidget_one = formPage.formWidgets[_tabNum];
        	if(!formWidget_one)return;
        	var formWidget = formWidget_one.formWidget;
        	var strID = formWidget.strID;
        	
    		$("#" + strID).focus();
    		if(formWidget.type == 8){
    			var listID = formWidget.strFgID;
    			$("#" +formWidget.inputID).focus();
    			$("#" + listID).trigger("click",{ inputid: formWidget_one.inputID });
    		}
        }

        //Doc View 消息响应
        function _onPreDocViewResize () {
            var scale = _readerApp.getMainView().getDocView().getScale();
            for (var key in _initedPageList) {
                if (_initedPageList[key] != null)
                	_initedPageList[key].changeSize(scale);
            }
        }
    };


    exports.createPlugin = function (readerApp) {
        var formPlugin = new WebPDF.CFormPlugin(readerApp);
        WebPDF.g_pFormPlugin = formPlugin;
        WebPDF.g_formValue = new WebPDF.FormValue();
        return formPlugin;
    };

});